package com.hcf.project.common.web;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.hcf.project.common.convention.errorcode.BaseErrorCode;
import com.hcf.project.common.convention.exception.AbstractException;
import com.hcf.project.common.convention.result.Result;
import com.hcf.project.common.convention.result.ResultTool;
import jakarta.servlet.http.HttpServletRequest;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Optional;

/**
 * 全局异常处理器
 */
@Component
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 拦截参数验证异常
     */
    @SneakyThrows
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result<Void> handleValidationExceptions(HttpServletRequest request, MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        // 获取字段级别的校验信息
        FieldError firstFieldError = CollectionUtil.getFirst(bindingResult.getFieldErrors());
        String exceptionStr = Optional.ofNullable(firstFieldError)
                .map(FieldError::getDefaultMessage)
                .orElse(StrUtil.EMPTY);
        log.error("[{}] {} [ex] {}", request.getMethod(), getUrl(request), exceptionStr);
        return ResultTool.failure(BaseErrorCode.CLIENT_ERROR.code(), exceptionStr);
    }

    /**
     * 拦截应用内抛出的异常
     */
    @ExceptionHandler(value = AbstractException.class)
    public Result<Void> handleAbstractException(HttpServletRequest request, AbstractException e) {
        if(e.getCause() != null){
            log.error("[{}] {} [ex] {}", request.getMethod(), request.getRequestURL().toString(), e.toString(), e.getCause());
            return ResultTool.failure(e);
        }
        log.error("[{}] {} [ex] {}", request.getMethod(), request.getRequestURL().toString(), e.toString());
        return ResultTool.failure(e);
    }

    /**
     * 拦截未捕获异常
     */
    @ExceptionHandler(value = Throwable.class)
    public Result handleException(HttpServletRequest request, Throwable throwable) {
        log.error("[{}] {}", request.getMethod(), getUrl(request), throwable);
        return ResultTool.failure();
    }


    /**
     * 获得带参数的访问URL
     */
    private String getUrl(HttpServletRequest request){
        if(StringUtils.isEmpty(request.getQueryString())){
            return request.getRequestURL().toString();
        }
        return request.getRequestURL().append("?").append(request.getQueryString()).toString();
    }


}
